package fi.laurea.jsonbus;

import java.io.IOException;

import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Sender {

	private String exhangeName = null;
	private Connection connection = null;
	private Channel channel = null;
	private Gson gson;

	public Sender(String exhangeName) {
		this.exhangeName = exhangeName;
		this.gson = new Gson();
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("109.75.176.134");
		try {
			connection = factory.newConnection();
			channel = connection.createChannel();
			channel.exchangeDeclare(this.exhangeName, "topic");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void sendGlobally(Object object) {

		String message = gson.toJson(object);

		try {
			channel.basicPublish(exhangeName, "all", null, message.getBytes());
		} catch (IOException e) {

			e.printStackTrace();
		}
		System.out.println(" [x] Sent '" + "all" + "':'" + message + "'");
	}

	public void sendToId(Object object, String listerId) {
		String message = gson.toJson(object);
		try {
			channel.basicPublish(exhangeName, listerId, null,
					message.getBytes());
		} catch (IOException e) {

			e.printStackTrace();
		}
		System.out.println(" [x] Sent '" + listerId + "':'" + message + "'");
	}

}
